<?php

/*   Image Works
 *   
 * Classe responsável pela manipulação de arquivos de imagens
 * @package Image
 *
 */

class Image_Work {

    private $ci;
    private $settings = array(
        'image_library' => 'gd2',
        'resize' => true,
        'thumbnail' => true,
        'quality' => 95,
        'small' => true);
    private $image_lib;
    private $errors = array();
    private $info = array();

    function __construct($props = array()) {

        if (count($props) > 0) {
            $this->initialize($props);
        }

        $this->ci = & get_instance();
        $this->ci->load->library(array('image_lib'));
        $this->image_lib = $this->ci->image_lib;
        $this->ci->config->load('image_lib');
        $this->settings = array_merge($this->settings, config_item('image_lib'));
        log_message('debug', "Image Working Class Initialized");
    }

    function initialize($props = array()) {
        if (count($props) > 0) {
            foreach ($props as $key => $val) {
                $this->settings[$key] = $val;
            }
        }
    }

    function run() {

        if ($this->_upload() !== false) {
            if ($this->_resize() === false)
                return false;
            if ($this->_crop() === false)
                return false;
            if ($this->_watermark() === false)
                return false;
            if ($this->_small() === false)
                return false;
            if ($this->_thumb() === false)
                return false;
        }
    }

    function data() {
        return $this->info;
    }

    /**
     * _Crop
     * 
     * Image crop
     * 
     * @access private
     * @return boolean
     */
    function _crop() {
        if (isset($this->settings['source_image']) && $this->settings['image_crop']):
            //resize 
            //if ($this->_resize()) {
            $imageSize = $this->image_lib->get_image_properties($this->settings['source_image'], TRUE);
            $config['image_library'] = $this->settings['image_library'];
            $config['source_image'] = $this->settings['source_image'];
            $config['create_thumb'] = false;
            $config['new_image'] = $this->settings['source_image'];
            $config['maintain_ratio'] = FALSE;
            $config['quality'] = $this->settings['quality'];
            $config['width'] = $this->settings['image_w'];
            $config['height'] = $this->settings['image_h'];
            //centered image
            $config['y_axis'] = (($imageSize['height'] / 2) - ($config['height'] / 2));
            $config['x_axis'] = (($imageSize['width'] / 2) - ($config['width'] / 2));
            $this->image_lib->initialize($config);
            if (!$this->image_lib->crop()) {
                $this->errors[] = $this->image_lib->display_errors();
                return false;
            }
        endif;
    }

    function _thumb() {
        if ($this->settings['thumbnail']):
            $apply_thumb = false;
            $config = array();
            $config['quality'] = 95;
            $config['image_library'] = $this->settings['image_library'];
            $config['maintain_ratio'] = TRUE;
            if ($this->settings['image_thumb_percent'] > 0):
                $apply_thumb = true;
                $config['width'] = ceil($this->settings['image_w'] * $this->settings['image_thumb_percent']) / 100;
                $config['height'] = ceil($this->settings['image_h'] * $this->settings['image_thumb_percent']) / 100;

            endif;
            if ($this->settings['image_thumb_w'] > 0 || $this->settings['image_thumb_h'] > 0):
                $apply_thumb = true;
                $config['width'] = $this->settings['image_thumb_w'];
                $config['height'] = $this->settings['image_thumb_h'];
            endif;
            $config['source_image'] = $this->settings['source_image'];
            $config['new_image'] = preg_replace("#" . $this->settings['upload_path'] . "#", rtrim($this->settings['upload_path'], '/') . '/thumbs/', $this->settings['source_image']);
            $config['create_thumb'] = TRUE;
            if ($apply_thumb):
                $this->image_lib->initialize($config);
                if (!$this->image_lib->resize()):
                    $this->errors[] = $this->image_lib->display_errors();
                    return false;
                endif;
            endif;
        endif;
    }

    function _small() {
        if ($this->settings['small']):
            $apply_small = false;
            $config = array();
            $config['quality'] = 95;
            $config['image_library'] = $this->settings['image_library'];
            $config['maintain_ratio'] = TRUE;
            if ($this->settings['image_small_percent'] > 0):
                $apply_small = true;
                $config['width'] = ceil($this->settings['image_w'] * $this->settings['image_small_percent']) / 100;
                $config['height'] = ceil($this->settings['image_h'] * $this->settings['image_small_percent']) / 100;

            endif;
            if ($this->settings['image_small_w'] > 0):
                $apply_small = true;
                $config['width'] = $this->settings['image_w'];
                $config['height'] = $this->settings['image_h'];
            endif;

            $config['source_image'] = $this->settings['source_image'];
            $config['new_image'] = preg_replace("#" . $this->settings['upload_path'] . "#", rtrim($this->settings['upload_path'], '/') . '/smalls/', $this->settings['source_image']);
            $config['create_thumb'] = TRUE;

            if ($apply_small):
                $this->image_lib->initialize($config);
                if (!$this->image_lib->resize()):
                    $this->errors[] = $this->image_lib->display_errors();
                    return false;

                endif;
            endif;
        endif;
    }

    function _resize() {
        if ($this->settings['resize']):
            $config['image_library'] = $this->settings['image_library'];
            $config['maintain_ratio'] = TRUE;
            $config['quality'] = 95;
            $config['master_dim'] = 'width';


            $config['width'] = $this->settings['image_w'] + (($this->settings['image_w'] * $this->settings['sangria']) / 100);
            $config['height'] = $this->settings['image_h'] + (($this->settings['image_h'] * $this->settings['sangria']) / 100);
            $config['source_image'] = $this->settings['source_image'];
            $this->image_lib->initialize($config);
            if (!$this->image_lib->resize()):
                $this->errors[] = $this->image_lib->display_errors();

                return false;
            endif;
        endif;
    }

    function _rotate() {
        
    }

    function _upload() {
        if (isset($this->settings['upload_archive'])):

            $config = array();
            $config['upload_path'] = $this->settings['upload_path'];
            $config['allowed_types'] = $this->settings['allowed_types'];
            $config['max_size'] = $this->settings['max_size'];
            $config['encrypt_name'] = $this->settings['encrypt_name'];
            $config['overwrite'] = $this->settings['overwrite'];

            $this->ci->load->library('upload');
            $this->ci->upload->initialize($config);
            $this->image_lib->clear();
            if (!$this->ci->upload->do_upload($this->settings['upload_archive'])):
                //$this->errors[] = print_r($_FILES[$this->settings['upload_archive']],true);
                $this->errors[] = $this->ci->upload->display_errors();
                return false;
            endif;
            $info = $this->ci->upload->data();
            $this->info = $info;


            $this->settings['upload_path'] = $info['file_path'];
            $this->settings['source_image'] = $info['full_path']; //;$this->settings['upload_path'] . $info['raw_name'] . $info['file_ext'];
        endif;
    }

    function delete($file) {
        //  ini_set('display_errors',1);
        $folders = array('', 'thumbs', 'smalls');
        $link_file = preg_split('#\/#', $file);
        $index = count($link_file) - 1;
        $file_name = $link_file[$index];
        unset($link_file[$index]);
        $delete = 0;
        $data = array();
        $data['success'] = false;
        foreach ($folders as $dir):
            $filename = rtrim(implode('/', $link_file), '/') . '/' . $dir . '/' . $file_name;
            $a_not_deleted = array('name' => $file_name, 'path' => $filename, 'deleted' => false);
            if (file_exists($filename)):
                log_message('debug', "Class Image_work delete : {$filename}");
                unlink($filename);
                $a_not_deleted = array('name' => $file_name, 'path' => $filename, 'deleted' => true);
                $delete+=1;
            endif;

            $data['files'][] = $a_not_deleted;
        endforeach;
        if ($delete > 0):
            $data['success'] = true;
        endif;

        return $data;
    }

    function _watermark() {
        $watermark = false;
        if (!$this->settings['image_watermark']) {
            return;
        }
        if (strlen($this->settings['image_watermark_text']) > 2):
            $watermark = true;
            $config['wm_text'] = $this->settings['image_watermark_text'];
            $config['wm_type'] = 'text';
        endif;
        if (preg_match('#(\.gif|\.GIF|\.jgp|\.JPG\|\.JPEG|\.jpeg|\.png|\.PNG)$#', $this->settings['image_watermark_image'])):
            $watermark = true;
            $config['wm_type'] = 'overlay';
            $config['wm_overlay_path'] = $this->settings['image_watermark_image'];
        endif;
        $config['source_image'] = $this->settings['source_image'];
        $config['wm_font_path'] = BASEPATH . 'fonts/texb.ttf';
        $config['wm_font_size'] = '50';
        $config['wm_font_color'] = 'ffffff';
        $config['wm_vrt_alignment'] = 'middle';
        $config['wm_hor_alignment'] = 'center';
        $config['wm_opacity'] = 30;
        $config['wm_shadow_color'] = '333333';
        $config['wm_shadow_distance'] = 2;
        if ($watermark):

            $this->image_lib->clear();
            $this->image_lib->initialize($config);
            if (!$this->image_lib->watermark()) {
                $this->errors[] = $this->image_lib->display_errors();
                return false;
            }

        endif;
    }

    function get_errors() {
        if (count($this->errors) == 0):
            return false;
        endif;
        return implode('<br/>', $this->errors);
    }

}
